package com.ecommerce.controller;

import com.ecommerce.entity.Address;
import com.ecommerce.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/addresses")
@CrossOrigin(origins = "*")
public class AddressController {

    @Autowired
    private AddressService addressService;

    // 获取用户的所有地址
    @GetMapping
    public ResponseEntity<Map<String, Object>> getUserAddresses(@RequestParam Long userId) {
        Map<String, Object> result = addressService.getUserAddresses(userId);
        return ResponseEntity.ok(result);
    }

    // 获取用户的默认地址
    @GetMapping("/default")
    public ResponseEntity<Map<String, Object>> getDefaultAddress(@RequestParam Long userId) {
        Map<String, Object> result = addressService.getDefaultAddress(userId);
        return ResponseEntity.ok(result);
    }

    // 根据ID获取地址详情
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getAddressById(
            @RequestParam Long userId,
            @PathVariable Long id) {
        Map<String, Object> result = addressService.getAddressById(userId, id);
        return ResponseEntity.ok(result);
    }

    // 创建新地址
    @PostMapping
    public ResponseEntity<Map<String, Object>> createAddress(
            @RequestParam Long userId,
            @RequestBody Address addressData) {
        Map<String, Object> result = addressService.createAddress(userId, addressData);
        return ResponseEntity.ok(result);
    }

    // 更新地址
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateAddress(
            @RequestParam Long userId,
            @PathVariable Long id,
            @RequestBody Address addressData) {
        Map<String, Object> result = addressService.updateAddress(userId, id, addressData);
        return ResponseEntity.ok(result);
    }

    // 删除地址
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteAddress(
            @RequestParam Long userId,
            @PathVariable Long id) {
        Map<String, Object> result = addressService.deleteAddress(userId, id);
        return ResponseEntity.ok(result);
    }

    // 设置默认地址
    @PutMapping("/{id}/default")
    public ResponseEntity<Map<String, Object>> setDefaultAddress(
            @RequestParam Long userId,
            @PathVariable Long id) {
        Map<String, Object> result = addressService.setDefaultAddress(userId, id);
        return ResponseEntity.ok(result);
    }
} 